import os
import sys

service_py_template = """# 由pmm管理工具自动生成
# 微服务 {0}
# Tips: 需要在server.py中引用

from python_microservice_sdk import service


@service
def {1}(*args, **kwargs) -> Any:
    pass
"""

service_py_mini_template = """

@service
def {0}(*args, **kwargs) -> Any:
    pass
"""

import_template = "import {0} as _\n"


def insert_service_import(project_dir: str, package: str):
    import_text = import_template.format(package)
    with open(os.path.join(project_dir, "server.py"), "r+", encoding="utf-8") as fp:
        lines = fp.readlines()
        if import_text not in lines:
            cur_line_no = 0
            for line_no, line in enumerate(lines):
                if line.isspace() or line == "" or line.startswith("#"):
                    continue

                if line.startswith("import ") or line.startswith("from "):
                    cur_line_no = line_no
                else:
                    break
            lines.insert(cur_line_no+1, import_text)

            fp.seek(0, os.SEEK_SET)
            fp.writelines(lines)


def run(project_dir: str):

    args = sys.argv[3:]
    if len(args) == 0:
        print("create_service需要至少有一个service_name的参数!")
        exit(-1)

    service_name = args[0]
    in_which_package = service_name
    if len(args) > 1:
        in_which_package = args[1]
    package_basename = in_which_package.split(".")[-1]
    package_path = in_which_package.replace(".", "/")

    output_filename = os.path.join(project_dir, "%s.py" % package_path)
    output_dir = os.path.dirname(output_filename)
    os.makedirs(output_dir, exist_ok=True)

    if not os.path.exists(output_filename):
        with open(output_filename, "w", encoding="utf-8")as fp:
            fp.write(service_py_template.format(
                package_basename, service_name))

    else:
        with open(output_filename, 'r+', encoding="utf-8") as fp:
            lines = fp.readlines()
            for line in lines:
                if line.startswith("def %s(" % service_name):
                    print("已存在相同的方法'%s'" % service_name)
                    exit(-1)

            fp.seek(0, os.SEEK_END)
            fp.write(service_py_mini_template.format(service_name))

    insert_service_import(project_dir, in_which_package)
